package com.vito.dcs.intface.service.impl;

import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.BadSqlGrammarException;

import com.alibaba.dubbo.config.annotation.Service;
import com.alibaba.fastjson.JSONObject;
import com.mysql.jdbc.exceptions.jdbc4.MySQLSyntaxErrorException;
import com.vito.base.model.Result;
import com.vito.dcs.common.util.SplitTableUtil;
import com.vito.dcs.intface.IntfaceService;
import com.vito.dcs.intface.dao.IntfaceMapper;

@Service
public class IntfaceServiceImpl implements IntfaceService{

	@Autowired
	private IntfaceMapper intfaceMapper;
	
	@Override
	public List<HashMap<String, String>> queryPileKey(Map<String, String> map) {
		return intfaceMapper.queryPileKey(map);
	}
	
	@Override
	public HashMap<String, String> findCenterCoor(Map<String,String> map) {
		
		List<HashMap<String,String>> centerCoorList = null;
		
		map.put("tableName", SplitTableUtil.getTableName( (String)map.get("time") ));
		
		try {
			/**
			 * 实时
			 */
			if("0".equals(map.get("isHistory"))){
				
				Map<String, Object> queryLastTPJData = intfaceMapper.queryLastTPJData(map);
				if(queryLastTPJData != null && queryLastTPJData.keySet().size() > 0){
					
					map.put("last_lng", queryLastTPJData.get("last_lng").toString());
					map.put("last_lat", queryLastTPJData.get("last_lat").toString());
					
					String queryMinLngAndLat = intfaceMapper.queryMinLngAndLat(map);
					
					if(queryMinLngAndLat != null && queryMinLngAndLat.length() > 0){
						String[] split = queryMinLngAndLat.split("@");
						if(split[0].length() > 0 && split[1].length() > 0){
							map.put("min_lng", split[0]);
							map.put("min_lat", split[1]);
							centerCoorList = intfaceMapper.findCenterCoor1(map);
							if(centerCoorList == null || centerCoorList.size() == 0){
								centerCoorList = intfaceMapper.findGpsCoor(map);
							}
						}
					}
				} else {
					centerCoorList = intfaceMapper.findCenterCoor(map);
					if(centerCoorList == null || centerCoorList.size() == 0){
						centerCoorList = intfaceMapper.findGpsCoor(map);
					}
				}
				
				if(centerCoorList != null && centerCoorList.size() > 0){
					return centerCoorList.get(0);
				} else {
					return null;
				}
			} else {
				/**
				 * 历史轨迹
				 */
				
				centerCoorList = intfaceMapper.findCenterCoor(map);
				if(null!=centerCoorList && centerCoorList.size()>0){
					return centerCoorList.get(0);
				}else{
					centerCoorList = intfaceMapper.findGpsCoor(map);
					if(centerCoorList != null && centerCoorList.size() > 0){
						return centerCoorList.get(0);
					} else {
						return null;
					}
				}
			}
		} catch (Exception e) {
			
			centerCoorList = intfaceMapper.findGpsCoor(map);
			if(centerCoorList != null && centerCoorList.size() > 0){
				return centerCoorList.get(0);
			} else {
				BadSqlGrammarException  b = (BadSqlGrammarException) e;
				Throwable cause = b.getCause();
				MySQLSyntaxErrorException m = null;
				try {
					 m = (MySQLSyntaxErrorException) cause;
				} catch (Exception e2) {
					throw e;
				}
				if(m != null && m.getErrorCode() == 1146){
					try {
						return null;
					} catch (Exception e2) {
						throw e2;
					}
					
				} else {
					throw e;
				}
			}
			
		}
		
	}
	
	@Override
	public List<HashMap<String, String>> querySysConstructionVehicleByAreaId(Map<String, String> map) {
		List<HashMap<String,String>> constructionVehicleList = intfaceMapper.querySysConstructionVehicleByAreaId(map);
		return constructionVehicleList;
	}
	
	@Override
	public Result querySectionAndConstructionInfo(Map<String, String> map) {
		Result rs = new Result();
		JSONObject json = new JSONObject();
		try {
			map.put("tableName", SplitTableUtil.getTableName( (String)map.get("time") ));
			if("now".equals(map.get("par"))){
				//查询车辆的实时轨迹信息
				HashMap<String,Object> conPMap = intfaceMapper.findDataInfoByConstructId(map);
				if(null!=conPMap){
					rs.setMsg("查询成功");
				}else{
					rs.setMsg("暂无轨迹信息");
				}
				json.put("construction", conPMap);
			}else if("all".equals(map.get("par"))){
				//查询车辆当天所有的轨迹信息
				List<HashMap<String,Object>> allConPMap = intfaceMapper.findAllDataInfoByConstructId(map);
				if(null!=allConPMap && allConPMap.size()>0){
					rs.setMsg("查询成功");
				}else{
					rs.setMsg("暂无轨迹信息");
				}
				json.put("construction", allConPMap);
			}
			rs.setCode(Result.CODE_OK);
			rs.setData(json);
		} catch (Exception e) {
			e.printStackTrace();
			rs.setCode(Result.CODE_ERROR);
			rs.setMsg("查询失败");
		}
		return rs;
	}

	private String trimZero(String s) {
	    if (s.indexOf(".") > 0) {
	        // 去掉多余的0
	        s = s.replaceAll("0+?$", "");
	        // 如最后一位是.则去掉
	        s = s.replaceAll("[.]$", "");
	    }
	    return s;
	}

	@Override
	public Result queryAllSectionAndConstructionInfo(Map<String, String> map) {
		Result rs = new Result();
		JSONObject json = new JSONObject();
		map.put("tableName", SplitTableUtil.getTableName( (String)map.get("time") ));
		try {
			List<HashMap<String,Object>> construncList = intfaceMapper.findAllConstInfo(map);
			//查询车辆的轨迹信息
			if(null!=construncList && construncList.size()>0){
				rs.setMsg("查询成功");
			}else{
				rs.setMsg("暂无轨迹信息");
			}
			
			Map<String, Object> resMap = processData(construncList);
			
			json.put("construction", resMap);
			rs.setCode(Result.CODE_OK);
			rs.setData(json);
		} catch (Exception e) {
			
			BadSqlGrammarException  b = (BadSqlGrammarException) e;
			Throwable cause = b.getCause();
			MySQLSyntaxErrorException m = null;
			try {
				 m = (MySQLSyntaxErrorException) cause;
			} catch (Exception e2) {
				throw e;
			}
			if(m != null && m.getErrorCode() == 1146){
				try {
					rs.setMsg("暂无轨迹信息");
					json.put("construction", new HashMap<String,Object>());
					rs.setCode(Result.CODE_OK);
					rs.setData(json);
				} catch (Exception e2) {
					throw e2;
				}
				
			} else {
				throw e;
			}
		}
		return rs;
	}

	@Override
	public HashMap<String, String> findLayerByTime(Map<String, String> map) {
		//查询施工时间对应面层
		return intfaceMapper.findLayerByTime(map);
	}

	@Override
	public HashMap<String,String> findConstructionInfoByConId(Map<String, String> map) {
		return intfaceMapper.findConstructionInfoByConId(map);
	}

	@Override
	public Result queryRealTimeTrajectory(Map<String, String> map) {
		Result rs = new Result();
		JSONObject json = new JSONObject();
		List<HashMap<String,Object>> allConPMap = null;
		
		try {
			
			if("0".equals(map.get("isFirst"))){
				map.put("tableName", SplitTableUtil.getTableName( new Date() ));
				
				/*Map<String, Object> queryLastTPJData = intfaceMapper.queryLastTPJData(map);
				if(queryLastTPJData != null && queryLastTPJData.keySet().size() > 0){
					map.put("last_lng", queryLastTPJData.get("last_lng").toString());
					map.put("last_lat", queryLastTPJData.get("last_lat").toString());
					
					// 第一种方式
					//allConPMap = intfaceMapper.queryRealTimeTrajectoryFirst(map);
					//第二种方式
					String queryMinLngAndLat = intfaceMapper.queryMinLngAndLat(map); 
					if(queryMinLngAndLat != null && queryMinLngAndLat.length() > 0){
						String[] split = queryMinLngAndLat.split("@");
						if(split[0].length() > 0 && split[1].length() > 0){
							map.put("min_lng", split[0]);
							map.put("min_lat", split[1]);
							allConPMap = intfaceMapper.queryRealTimeTrajectoryFirst1(map);
						}
					}
					
				} else {
					allConPMap = intfaceMapper.queryRealTimeTrajectory(map);
				}*/
				allConPMap = intfaceMapper.queryRealTimeTrajectory(map);
			} else if ("1".equals(map.get("isFirst"))) {
				map.put("tableName", SplitTableUtil.getTableName( (String)map.get("time") ));
				allConPMap = intfaceMapper.queryRealTimeTrajectory(map);
			}
			if(null!=allConPMap && allConPMap.size()>0){
				rs.setMsg("查询成功");
			}else{
				rs.setMsg("暂无轨迹信息");
			}
			
			/**
			 * 处理数据
			 */
			Map<String, Object> resMap = processData(allConPMap);
			
			json.put("construction", resMap);
			rs.setCode(Result.CODE_OK);
			rs.setData(json);
		} catch (Exception e) {
			BadSqlGrammarException  b = (BadSqlGrammarException) e;
			Throwable cause = b.getCause();
			MySQLSyntaxErrorException m = null;
			try {
				 m = (MySQLSyntaxErrorException) cause;
			} catch (Exception e2) {
				throw e;
			}
			if(m != null && m.getErrorCode() == 1146){
				try {
					rs.setMsg("暂无轨迹信息");
					json.put("construction", new HashMap<String,Object>());
					rs.setCode(Result.CODE_OK);
					rs.setData(json);
				} catch (Exception e2) {
					throw e2;
				}
				
			} else {
				throw e;
			}
		}
		return rs;
	}
	
	/**
	 * 封装返回的数据结构
	 * @param allConPMap
	 * @return
	 */
	private Map<String, Object> processData(
			List<HashMap<String, Object>> allConPMap) {
		Map<String,Object> resMap = new HashMap<String, Object>();
		for(int i = 0; i < allConPMap.size(); i ++){
			String conId = (String) allConPMap.get(i).get("conId");
			if(!resMap.containsKey(conId)){
				List<Map<String,Object>> list = new ArrayList<Map<String,Object>>();
				list.add(allConPMap.get(i));
				resMap.put(conId, list);
			} else {
				@SuppressWarnings("unchecked")
				List<Map<String,Object>> list = (List<Map<String, Object>>) resMap.get(conId);
				list.add(allConPMap.get(i));
			}
		}
		return resMap;
	}

}
